<template>
  <view>
    <quick-button></quick-button>
    <view class="order-list">
      <!-- 轮播图 -->
      <u-swiper
        :list="bannerList"
        height="200"
        indicator
        indicatorInactiveColor="#e5e5e5"
        indicatorActiveColor="#0bc5ae"
        indicatorStyle="bottom: 10px;"></u-swiper>

      <!-- 资费须知 -->
      <view class="section-header">
        <view class="section-title">资费须知</view>
      </view>
      <view class="order-card">
        <view class="instructions-item">
          <view class="instructions-title">基础服务费</view>
          <view class="instructions-content">
            <view class="content-item">
              · 服务类型：{{ serviceInfo.serverValue || "待选择" }}
            </view>
            <view class="content-item">
              · 服务单价：¥ {{ halfPrice || 0 }} / 天
            </view>
            <view class="content-item">
              · 服务天数：{{ dayCounts || 0 }} 天
            </view>
            <view class="content-item">
              · 小计：¥ {{ discountPrice || 0 }} （单价 × 天数）
            </view>
          </view>
        </view>
        <view class="instructions-item">
          <view class="instructions-title">费用总计</view>
          <view class="instructions-content">
            <view class="content-item">
              · 应付总额：¥ {{ discountPrice || 0 }}
            </view>
          </view>
        </view>
        <view class="instructions-item">
          <view class="instructions-title">支付与发票</view>
          <view class="instructions-content">
            <view class="content-item">
              · 支付方式：支持微信支付、现金支付。请在订单生成后
              30分钟内完成支付，否则订单将自动取消。
            </view>
            <view class="content-item">
              ·
              发票开具：我们可开具"护理服务费"类目的电子普通发票。如需开票，请在服务完成后7
              个工作日内，于"我的订单"页面中申请。
            </view>
          </view>
        </view>
      </view>

      <!-- 订单表单 -->
      <view class="section-header">
        <view class="section-title">填写订单信息</view>
      </view>
      <view class="order-card form-card">
        <!-- 优惠券选择 -->
        <view class="form-item" v-if="payment.length > 0">
          <view class="form-label required">优惠券</view>
          <view class="form-content">
            <view class="payment-box">
              <view
                class="payment-item"
                v-for="(item, index) in payment"
                :key="index"
                :class="{ selected: paymentId === item.id }"
                @tap="onPaymentChange(item.id)">
                {{ item.couponName }}
              </view>
            </view>
          </view>
        </view>

        <!-- 服务周期 -->
        <view class="form-item" v-if="billingType == 'daily'">
          <view class="form-label required">服务周期：{{ serviceTime }}</view>

          <!-- 4小时服务：预设时间段选择 -->
          <view class="form-content" v-if="serviceTime === '4小时'">
            <view style="display: flex; align-items: center">
              <view class="range-label">时间段：</view>
              <picker
                mode="selector"
                :range="timeRanges"
                :range-key="'label'"
                :value="selectedIndex"
                class="time-range-picker"
                :class="{ placeholder: !selectedRange.label }"
                @change="handleRangeChange">
                <view class="range-value">
                  {{ selectedRange.label || "请选择时间段" }}
                </view>
              </picker>
            </view>
          </view>

          <!-- 12小时服务：固定时间段 -->
          <view class="form-content" v-if="serviceTime === '12小时'">
            <view style="display: flex; align-items: center">
              <view class="range-label">时间段：</view>
              <view class="fixed-time">7:00 - 19:00</view>
            </view>
          </view>

          <!-- 24小时服务：时间选择区域 -->
          <view class="form-content" v-if="serviceTime === '24小时'">
            <view
              class="cycle-item"
              @click="openTimePicker('start')"
              :class="{ active: activeTimeType === 'start' }">
              <view class="cycle-label">开始时间：</view>
              <view
                class="cycle-value"
                :class="{ placeholder: !startDateTime }">
                {{ startDateTime || "请选择开始时间 >>" }}
              </view>
            </view>
            <view
              class="cycle-item"
              @click="openTimePicker('end')"
              :class="{ active: activeTimeType === 'end' }">
              <view class="cycle-label">结束时间：</view>
              <view class="cycle-value" :class="{ placeholder: !endDateTime }">
                {{ endDateTime || "请选择结束时间 >>" }}
              </view>
            </view>
          </view>

          <!-- 通用日期选择 -->
          <view class="form-content">
            <view class="cycle-item" @click="openPicker">
              <view class="cycle-label">开始日期：</view>
              <view class="cycle-value" :class="{ placeholder: !startDay }">
                {{ startDay || "请选择开始日期 >>" }}
              </view>
            </view>
            <view class="cycle-item" @click="openPicker1" :disabled="!startDay">
              <view class="cycle-label">结束日期：</view>
              <view class="cycle-value" :class="{ placeholder: !endDay }">
                {{ endDay || "请选择结束日期 >>" }}
              </view>
            </view>
            <view class="cycle-count">已选择：{{ dayCounts || 0 }} 天</view>
          </view>
        </view>

        <!-- 选择医院 -->
        <view class="form-item">
          <view class="form-label required">就诊医院</view>
          <view class="form-content">
            <view class="select-item" @click="chooseHospital">
              <view class="select-value">{{ hospitalName }}</view>
            </view>
          </view>
        </view>

        <!-- 科室 -->
        <view class="form-item">
          <view class="form-label required">就诊科室</view>
          <view class="form-content">
            <view class="select-value">{{ departments }}</view>
          </view>
        </view>

        <!-- 就诊人 -->
        <view class="form-item">
          <view class="form-label required">被护理人</view>
          <view class="form-content">
            <view class="select-item" @click="toPatientList">
              <template v-if="Object.keys(patientInfo).length > 0">
                <view class="patient-info">
                  <view class="patient-main">
                    <view class="patient-name">
                      {{ patientInfo.patientName }}
                    </view>
                    <view class="patient-tag">
                      {{ patientInfo.patientSex }} ·
                      {{ patientInfo.patientAge }}岁
                    </view>
                  </view>
                  <view class="patient-desc">
                    {{
                      patientInfo.patientMedical ||
                      patientInfo.patientPdiagnose ||
                      "无特殊病情描述"
                    }}
                  </view>
                </view>
              </template>
              <template v-else>
                <view class="select-value placeholder">请选择被护理人 >></view>
              </template>
            </view>
          </view>
        </view>

        <!-- 护工性别 -->
        <view class="form-item">
          <view class="form-label">护工性别</view>
          <view class="form-content">
            <view class="select-item" @click="chooseSex">
              <view class="select-value" :class="{ placeholder: !sexValue }">
                {{ sexValue || "请选择护工性别 >>" }}
              </view>
            </view>
          </view>
        </view>

        <!-- 服务要求 -->
        <view class="form-item">
          <view class="form-label">服务备注</view>
          <view class="form-content">
            <textarea
              v-model="remake"
              placeholder="可填写特殊要求、身体状态或病症说明"
              class="textarea-item"
              placeholder-class="textarea-placeholder"></textarea>
          </view>
        </view>
      </view>

      <!-- 服务详情 -->
      <!-- <view class="section-header">
        <view class="section-title">服务详情</view>
      </view>
      <view class="service-card">
        <view class="service-item">
          <view class="service-label">服务类型</view>
          <view class="service-value">
            {{ serviceInfo.categoryCode || "医院陪诊" }}
          </view>
        </view>
        <view class="service-item">
          <view class="service-label">职责范围</view>
          <view class="service-value">
            {{
              serviceInfo.categoryValue ||
              "健康监测、生活和用药提醒、取送报告等"
            }}
          </view>
        </view>
        <view class="service-item">
          <view class="service-label">工作时长</view>
          <view class="service-value">
            {{ serviceInfo.categoryObject || serviceTime }}
          </view>
        </view>

        <view class="notice-section">
          <view class="notice-title">注意事项</view>
          <view class="notice-content">
            <view class="notice-item">
              1.
              信息真实性与告知义务：您已承诺所填写的患者健康状况、病史及行为习惯等信息真实准确。服务开始后，若护工评估发现实际情况与所选服务级别严重不符，我们将第一时间与您沟通调整。
            </view>
            <view class="notice-item">
              2.
              服务边界：护工提供生活照料与辅助性护理，非医疗行为，不承担医疗决策、执行医嘱等护士职责。患者出现病情变化请立即呼叫医护人员。
            </view>
            <view class="notice-item">
              3.
              物品准备：请提前备齐患者日常所需物品（尿不湿、护理垫、换洗衣物等），避免影响照护质量。
            </view>
            <view class="notice-item">
              4.
              沟通协作：建议与护工建立每日固定沟通时段，遇到问题可通过官方客服协调。
            </view>
            <view class="notice-item">
              5.
              安全约定：请妥善保管贵重财物，护工尽合理注意义务，非因护工失职造成的意外按法律规定界定责任。
            </view>
          </view>
        </view>

        <view class="promise-section">
          <view class="promise-title">我们的承诺</view>
          <view class="promise-list">
            <view
              class="promise-item"
              v-for="(item, index) in promiseList"
              :key="index">
              <image
                mode="aspectFit"
                :src="item.pic"
                class="promise-icon"></image>
              <view class="promise-content">
                <view class="promise-name">{{ item.name }}</view>
                <view class="promise-desc">{{ item.content }}</view>
              </view>
            </view>
          </view>
        </view>
      </view> -->

      <!-- 下单须知 -->
      <!-- <view class="section-header">
        <view class="section-title">下单须知</view>
      </view>
      <view class="instructions-card">
        <view class="instructions-item">
          <view class="instructions-title">重要告知</view>
          <view class="instructions-content">
            <view class="content-item">
              1.
              信息真实性：您确认订单中所有信息（患者健康状况、服务地址等）真实准确，因信息不实造成的后果自行承担。
            </view>
            <view class="content-item">
              2.
              服务范围：护工提供生活照护和非医疗性护理，不能替代执业医师和护士的诊疗行为，急症请呼叫120或医护人员。
            </view>
          </view>
        </view>
        <view class="instructions-item">
          <view class="instructions-title">订单与支付</view>
          <view class="instructions-content">
            <view class="content-item">
              1.
              合同成立：点击"立即支付"并成功付款后，服务合同即成立并具有法律约束力。
            </view>
            <view class="content-item">
              2. 价格确认：您确认知晓并同意所选服务类型的公示价格。
            </view>
          </view>
        </view>
        <view class="instructions-item">
          <view class="instructions-title">变更与取消政策</view>
          <view class="instructions-content">
            <view class="content-item">1. 客户方取消：</view>
            <view class="content-item indent">
              · 服务开始前24小时以上：免费取消，全额退款
            </view>
            <view class="content-item indent">
              · 服务开始前6小时：扣除订单费用30%作为违约金
            </view>
            <view class="content-item indent">
              · 服务开始前2小时：扣除50%违约金
            </view>
            <view class="content-item">
              2.
              平台方责任：若因平台原因导致服务无法履行，将第一时间通知您，可选择改期或取消并全额退款。
            </view>
          </view>
        </view>
        <view class="instructions-item">
          <view class="instructions-title">责任界定</view>
          <view class="instructions-content">
            <view class="content-item">
              1.
              护工责任：因护工未按服务规范操作造成患者人身或财产直接损害的，经核实后平台依法承担相应责任。
            </view>
            <view class="content-item">
              2.
              争议解决：因本协议引起的争议，双方友好协商；协商不成的，可向平台运营方所在地有管辖权的人民法院提起诉讼。
            </view>
          </view>
        </view>
      </view> -->
    </view>

    <!-- 底部支付栏 -->
    <view class="bottom-fixed-view">
      <view class="agreement-view" v-if="showDoc">
        <view class="select-button" @click="radioClick">
          <image
            src="../../static/tab_select_have.png"
            v-if="radioSelected"
            class="select-icon"></image>
          <image
            src="../../static/tab_select_not.png"
            v-else
            class="select-icon"></image>
        </view>
        <view class="agreement-text">
          我已阅读并同意
          <view class="agreement-link" @click="toAgreement">《用户协议》</view>
        </view>
      </view>
      <view class="pay-bar">
        <view class="pay-info">
          <view class="pay-label">共计：</view>
          <cn-money
            :money="discountPrice"
            :size="48"
            :showUnit="true"
            :discount="originalPrice"></cn-money>
        </view>
        <button
          class="pay-btn"
          @click="handleSubmit()"
          :disabled="!radioSelected && !orderId">
          提交订单
        </button>
      </view>
    </view>

    <!-- 日期选择器 -->
    <view @touchmove.stop.prevent="() => {}">
      <u-datetime-picker
        @cancel="closeTimePicker"
        :show="showTime"
        ref="datetimePicker"
        v-model="startDay1"
        @confirm="confirmTimePicker"
        :formatter="formatter"
        mode="date"
        :minDate="todayStr"></u-datetime-picker>
    </view>
    <view @touchmove.stop.prevent="() => {}">
      <u-datetime-picker
        @cancel="closeTimePicker1"
        :show="showTime1"
        :minDate="startDay1 || todayStr"
        ref="datetimePicker1"
        v-model="endDay1"
        @confirm="confirmTimePicker1"
        :formatter="formatter"
        mode="date"></u-datetime-picker>
    </view>

    <!-- 24小时服务的时间选择器（核心修复：格式匹配+简化逻辑） -->
    <view @touchmove.stop.prevent="() => {}">
      <u-datetime-picker
        @cancel="closeDateTimePicker"
        :show="showDateTimePicker"
        ref="dateTimePicker"
        v-model="currentDateTime"
        @confirm="confirmDateTimePicker"
        :formatter="timeFormatter"
        mode="time"
        :minHour="0"
        :maxHour="23"></u-datetime-picker>
    </view>

    <!-- 选择性别/医院弹窗 -->
    <u-action-sheet
      :show="showSex"
      :actions="actions"
      @close="showSex = false"
      @select="sexSelect"></u-action-sheet>
    <u-action-sheet
      :show="showHospital"
      :actions="hospital"
      @close="showHospital = false"
      @select="HospitalSelect"></u-action-sheet>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import PageInfo from "../../utils/pageutils.js";
import cnMoney from "../../components/cn-money/cn-money";
import * as wxPay from "../../common/api/wxPay.js";

// 接口导入
import {
  getNurseServe,
  saveCompantionOrder,
  getServiceById,
  couponList,
  Days,
} from "../../common/api/index.js";
// 工具函数
import {
  subscribeMessage,
  calculateDaysBetweenTimestamps,
} from "../../utils/index.js";

// 常量定义
const PROMISE_LIST = [
  {
    name: "专业培训",
    content: "培训上岗 更专心",
    pic: "../../static/icon_peixun.png",
  },
  {
    name: "持证上岗",
    content: "多证在手 更贴心",
    pic: "../../static/icon_chizheng.png",
  },
  {
    name: "技能熟练",
    content: "基础扎实 更安心",
    pic: "../../static/icon_jineng.png",
  },
  {
    name: "全面体检",
    content: "岗前体检 更放心",
    pic: "../../static/icon_tijian.png",
  },
];

export default {
  props: {
    isInIndex: { type: Boolean, default: false },
  },
  components: { cnMoney },
  data() {
    return {
      // 基础配置
      bannerList: [
        "https://applet.youtuyiliao.com/profile/upload/xiaochengxu/static/banner_01.png",
      ],
      promiseList: PROMISE_LIST,
      // 表单数据
      startDay: "", // 开始日期
      endDay: "", // 结束日期
      startDay1: null, // 开始日期时间戳
      endDay1: null, // 结束日期时间戳
      startDateTime: "", // 开始时间（HH:mm格式）
      endDateTime: "", // 结束时间（HH:mm格式）
      currentDateTime: "00:00", // 初始值设为标准格式，解决uView报错
      activeTimeType: "", // 当前操作类型（start/end）
      departments: "", // 科室
      remake: "", // 备注
      sexValue: "", // 护工性别
      hospitalValue: "", // 医院
      patientInfo: {}, // 就诊人信息

      // 选择器配置
      actions: [{ name: "男" }, { name: "女" }],
      hospital: [
        { name: "西京医院" },
        { name: "唐都医院" },
        { name: "西安交通大学第一附属医院" },
        { name: "西安交通大学第二附属医院" },
        { name: "西安红会医院" },
        { name: "第四军医大学口腔医院" },
        { name: "陕西省人民医院" },
      ],

      // 状态控制
      showSex: false,
      showHospital: false,
      showTime: false,
      showTime1: false,
      showDateTimePicker: false, // 时间选择器显示状态
      radioSelected: false,
      showDoc: true,
      isSubmit: true,
      todayStr: "",

      // 费用相关
      halfPrice: "",
      originalPrice: "0.00",
      discountPrice: "0.00",
      dayCounts: 0,
      totalPrice: "0.00",

      // 接口相关
      token: "",
      serverId: "",
      hospitalName: "",
      code: "",
      allData: [],
      list: [],
      serviceInfo: {},
      payment: [],
      paymentId: "",
      paymentItem: {},
      billingType: "daily",
      orderId: "",
      isUpdate: false,
      orderState: "",
      serviceTime: "",

      // 4小时服务预设时间段
      timeRanges: [
        { label: "7:00-11:00", value: { start: "07:00", end: "11:00" } },
        { label: "8:00-12:00", value: { start: "08:00", end: "12:00" } },
        { label: "9:00-13:00", value: { start: "09:00", end: "13:00" } },
        { label: "10:00-14:00", value: { start: "10:00", end: "14:00" } },
        { label: "11:00-15:00", value: { start: "11:00", end: "15:00" } },
        { label: "12:00-16:00", value: { start: "12:00", end: "16:00" } },
        { label: "13:00-17:00", value: { start: "13:00", end: "17:00" } },
        { label: "14:00-18:00", value: { start: "14:00", end: "18:00" } },
        { label: "15:00-19:00", value: { start: "15:00", end: "19:00" } },
      ],
      selectedIndex: 0,
      department: "",
      selectedRange: {},
    };
  },
  computed: {
    ...mapGetters({ pageInfo: "page/pageInfo" }),
    today() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
  mounted() {
    this.getCurrentDate();
  },
  onShow() {
    if (this.pageInfo?.choosePatient) {
      this.patientInfo = this.pageInfo.choosePatientInfo;
      this.$nextTick(() => this.$store.commit("page/setPageInfo", {}));
    }
  },
  async onLoad(opt) {
    console.log("订单详情：", opt);
    this.serviceTime = opt.serviceTime;
    this.token = uni.getStorageSync("App-Token");
    this.halfPrice = opt.amount;
    this.serverId = opt.serverId;
    this.hospitalName = opt.hospitalName;
    this.departments = opt.department;
    console.log(this.departments);
    this.code = opt.code;
    this.isUpdate = opt.isUpdate;
    this.orderId = opt.orderId || "";

    if (this.serviceTime === "4小时") {
      this.selectedRange = this.timeRanges[0];
    }

    if (this.isUpdate) {
      this.showDoc = false;
      await this.getEditOrderData();
    } else {
      await Promise.all([
        this.getServiceList(),
        this.getServiceDetail(),
        this.getCouponList(),
      ]);
    }
  },
  methods: {
    handleRangeChange(e) {
      const index = e.detail.value;
      this.selectedIndex = index;
      this.selectedRange = this.timeRanges[index];
    },

    formatter(type, value) {
      switch (type) {
        case "year":
          return `${value}年`;
        case "month":
          return `${value}月`;
        case "day":
          return `${value}日`;
        default:
          return value;
      }
    },

    timeFormatter(type, value) {
      switch (type) {
        case "hour":
          return `${value}时`;
        case "minute":
          return `${value}分`;
        default:
          return value;
      }
    },

    // 打开时间选择器（简化逻辑，确保显示）
    openTimePicker(type) {
      this.activeTimeType = type;
      // 回显已选时间，无则默认00:00
      this.currentDateTime =
        this[type === "start" ? this.startDateTime : this.endDateTime] ||
        "00:00";
      this.showDateTimePicker = true; // 直接显示选择器，去掉复杂的refs操作
    },

    // 确认时间选择（核心修复：匹配uView格式要求）
    confirmDateTimePicker(e) {
      if (!e?.value) {
        this.closeDateTimePicker();
        return;
      }

      // uView time模式返回的是HH:mm格式字符串，直接使用
      const selectedTime = e.value;
      // 验证格式（确保是HH:mm）
      const timeReg = /^([01]\d|2[0-3]):([0-5]\d)$/;
      if (!timeReg.test(selectedTime)) {
        uni.showToast({ title: "时间格式错误", icon: "none" });
        this.closeDateTimePicker();
        return;
      }

      // 赋值到对应变量
      if (this.activeTimeType === "start") {
        this.startDateTime = selectedTime;
      } else {
        this.endDateTime = selectedTime;
      }

      this.closeDateTimePicker();
    },

    // 关闭时间选择器
    closeDateTimePicker() {
      this.showDateTimePicker = false;
      this.activeTimeType = "";
    },

    getCurrentDate() {
      const currentDate = new Date();
      this.todayStr = currentDate.getTime();

      // 初始化时间状态
      this.startDay1 = null;
      this.endDay1 = null;
      this.startDay = "";
      this.endDay = "";
      this.startDateTime = "";
      this.endDateTime = "";
      this.currentDateTime = "00:00";
    },

    // 编辑订单时的时间回显（确保格式正确）
    formatTimeOnly(date) {
      try {
        if (!(date instanceof Date) || isNaN(date.getTime())) {
          throw new Error("无效的日期对象");
        }
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${hours}:${minutes}`;
      } catch (err) {
        return "00:00";
      }
    },

    async getServiceList() {
      try {
        const res = await getNurseServe();
        this.allData = res.data.data;
        const filterData =
          this.allData.filter((item) => item.code === this.code)[0]
            ?.nurseServersList || [];
        this.list = filterData;
      } catch (err) {
        console.error("获取服务列表失败", err);
        uni.showToast({ title: "服务列表加载失败", icon: "none" });
      }
    },

    async getServiceDetail() {
      try {
        const res = await getServiceById({ serverId: this.serverId });
        this.serviceInfo = res.data.data || {};
      } catch (err) {
        console.error("获取服务详情失败", err);
        uni.showToast({ title: "服务详情加载失败", icon: "none" });
      }
    },

    async getCouponList() {
      try {
        const res = await couponList({
          userId: uni.getStorageSync("USER_ID"),
          serverId: this.serverId,
        });
        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.payment = res.data.data;
          this.paymentId = res.data.data[0].id;
          this.paymentItem = res.data.data[0];
        }
      } catch (err) {
        console.error("获取优惠券失败", err);
      }
    },

    async getEditOrderData() {
      try {
        await this.getServiceList();
        if (this.pageInfo?.chooseOrder) {
          const orderInfo = this.pageInfo.chooseOrderInfo;
          this.patientInfo = orderInfo.nursePatient || {};
          this.startDay = orderInfo.serverStart;
          this.endDay = orderInfo.serverEnd;
          this.startDay1 = Date.parse(this.startDay);
          this.endDay1 = Date.parse(this.endDay);

          if (this.serviceTime === "24小时") {
            // 编辑时回显正确格式的时间
            if (orderInfo.startDateTime) {
              const date = new Date(orderInfo.startDateTime);
              this.startDateTime = this.formatTimeOnly(date);
            }
            if (orderInfo.endDateTime) {
              const date = new Date(orderInfo.endDateTime);
              this.endDateTime = this.formatTimeOnly(date);
            }
          } else if (this.serviceTime === "4小时" && orderInfo.timePeriod) {
            const rangeIndex = this.timeRanges.findIndex(
              (r) => r.label === orderInfo.timeRange
            );
            if (rangeIndex !== -1) {
              this.selectedIndex = rangeIndex;
              this.selectedRange = this.timeRanges[rangeIndex];
            }
          }

          this.serviceInfo = {
            categoryValue: orderInfo.serverValueList?.join(",") || "",
            categoryPrice: orderInfo.serverPrice || "",
            monthPrice: orderInfo.serverMonthPrice || "",
            categoryObject: orderInfo.categoryObject || "",
            serverValue: orderInfo.serverValue || "",
            specialOfferPrice: orderInfo.specialOfferPrice || "",
          };
          this.hospitalValue = orderInfo.companionVisitHospital || "";
          this.departments = orderInfo.companionVisitDepartments || "";
          this.sexValue = orderInfo.companionVisitSex || "";
          this.remake = orderInfo.companionVisitRemake || "";
          this.computeCount();
          this.orderState = orderInfo.orderState;
          this.serverCycle = orderInfo.serverCycle;
          this.radioSelected = true;
          this.$nextTick(() => this.$store.commit("page/setPageInfo", {}));
        }
      } catch (err) {
        console.error("获取编辑订单数据失败", err);
        uni.showToast({ title: "订单数据加载失败", icon: "none" });
      }
    },

    computeCount() {
      this.originalPrice = "0.00";

      if (this.startDay1 && this.endDay1) {
        const start = new Date(this.startDay1);
        const end = new Date(this.endDay1);
        const timeDiff = end.getTime() - start.getTime();
        this.dayCounts = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
      } else {
        this.dayCounts = 0;
      }

      const unitPrice = Number(this.halfPrice) || 0;
      this.discountPrice = (this.dayCounts * unitPrice).toFixed(2);
      this.totalPrice = this.discountPrice;

      if (this.paymentItem?.discountAmount) {
        const finalPrice = Math.max(
          0,
          this.totalPrice - Number(this.paymentItem.discountAmount)
        );
        this.discountPrice = finalPrice.toFixed(2);
      }
    },

    formatTime(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 表单校验
    checkForm() {
      const msg = (text) => uni.showToast({ title: text, icon: "none" });

      if (!this.patientInfo?.patientId) {
        msg("请选择被护理人");
        return false;
      }
      if (!this.departments.trim()) {
        msg("请输入就诊科室");
        return false;
      }
      if (!this.startDay || !this.endDay) {
        msg("请选择服务起止日期");
        return false;
      }
      if (this.serviceTime === "4小时" && !this.selectedRange.label) {
        msg("请选择具体服务时间段");
        return false;
      }
      if (this.serviceTime === "24小时" && !this.startDateTime) {
        msg("请选择开始时间");
        return false;
      }
      if (this.serviceTime === "24小时" && !this.endDateTime) {
        msg("请选择结束时间");
        return false;
      }
      if (this.dayCounts <= 0) {
        msg("服务天数不能为0");
        return false;
      }
      if (!this.orderId && !this.radioSelected) {
        msg("请勾选用户协议");
        return false;
      }
      return true;
    },

    async handleSubmit() {
      if (!this.isSubmit) return;
      if (!this.checkForm()) return;

      this.isSubmit = false;
      uni.showLoading({ title: "提交中..." });

      try {
        const params = {
          companionVisitAmout: this.totalPrice,
          companionVisitServer: this.serverId,
          companionVisitHospital: this.hospitalName,
          companionVisitDepartments: this.departments.trim(),
          patientId: this.patientInfo.patientId,
          userId: this.patientInfo.patientUserId,
          companionVisitTime: this.startDay, //开始日期
          companionVisitEndTime: this.endDay, //结束日期
          companionVisitSex: this.sexValue || "",
          companionVisitRemake: this.remake.trim() || "",
          isFlag: 1,
          openId: uni.getStorageSync("openid_key"),
          couponId: this.paymentId || "",
        };

        let timeRangeInfo = {};
        if (this.serviceTime === "4小时") {
          timeRangeInfo = {
            timePeriod: this.selectedRange.label,
            startTime: this.selectedRange.value.start,
            endTime: this.selectedRange.value.end,
          };
        } else if (this.serviceTime === "12小时") {
          timeRangeInfo = {
            timePeriod: "7:00-19:00",
            startTime: "07:00",
            endTime: "19:00",
          };
        } else if (this.serviceTime === "24小时") {
          timeRangeInfo = {
            startDate: this.startDay,
            endDate: this.endDay,
            timePeriod: this.startDateTime + "-" + this.endDateTime,
            // startTime: this.startDateTime,  // 直接传递HH:mm格式
            // endTime: this.endDateTime       // 直接传递HH:mm格式
          };
        }
        Object.assign(params, timeRangeInfo);

        console.log("提交订单参数:", params);

        if (this.orderId) {
          params.orderId = this.orderId;
          uni.showToast({ title: "订单修改成功", icon: "success" });
          setTimeout(() => uni.navigateBack({ delta: 1 }), 1500);
        } else {
          const res = await saveCompantionOrder(params);
          if (res.data.code === 200) {
            uni.showToast({ title: "订单提交成功", icon: "success" });
            setTimeout(() => {
              uni.setStorageSync("nav_to_nurse_index", 1);
              uni.reLaunch({ url: "/nursingWorkerPages/pages/index/vndex" });
            }, 1500);
            // this.sendMsg();
          }
        }
      } catch (err) {
        console.error("提交订单失败", err);
        uni.showToast({ title: "订单提交失败，请重试", icon: "none" });
      } finally {
        uni.hideLoading();
        this.isSubmit = true;
      }
    },
    // sendMsg() {
    //   subscribeMessage({
    //     openId: uni.getStorageSync("openid_key"),
    //     orderNumber: this.orderDetail.orderId ? this.orderDetail.orderId : "",
    //   });
    // },

    openPicker() {
      if (this.startDay1 === null) this.startDay1 = this.todayStr;
      this.$refs.datetimePicker.innerValue = this.startDay1;
      this.showTime = true;
    },
    openPicker1() {
      if (!this.startDay) {
        uni.showToast({ title: "请先选择开始日期", icon: "none" });
        return;
      }
      if (this.endDay1 === null || this.endDay1 < this.startDay1)
        this.endDay1 = this.startDay1;
      this.$refs.datetimePicker1.innerValue = this.endDay1;
      this.showTime1 = true;
    },
    confirmTimePicker(e) {
      this.startDay = this.formatTime(e.value);
      this.startDay1 = e.value;
      this.showTime = false;

      if (!this.endDay || this.endDay1 < this.startDay1) {
        this.endDay1 = this.startDay1;
        this.endDay = this.startDay;
      }
      this.computeCount();
    },
    confirmTimePicker1(e) {
      this.endDay = this.formatTime(e.value);
      this.endDay1 = e.value;
      if (this.serviceTime == "24小时") {
        const params = {
          startDate: this.startDay,
          endDate: this.endDay,
          startTime: this.startDateTime,
          endTime: this.endDateTime,
        };
        console.log(params);
        Days(params).then((res) => {
          console.log(res.data.msg);
          this.dayCounts = res.data.msg;
          const unitPrice = Number(this.halfPrice) || 0;
          this.discountPrice = (this.dayCounts * unitPrice).toFixed(2);
          this.totalPrice = this.discountPrice;
          this.showTime1 = false;
        });
      } else {
        this.showTime1 = false;
        this.computeCount();
      }
    },
    closeTimePicker() {
      this.showTime = false;
    },
    closeTimePicker1() {
      this.showTime1 = false;
    },

    chooseSex() {
      this.showSex = true;
    },
    chooseHospital() {
      this.showHospital = true;
    },
    sexSelect(e) {
      this.sexValue = e.name;
      this.showSex = false;
    },
    HospitalSelect(e) {
      this.hospitalValue = e.name;
      this.showHospital = false;
    },

    onPaymentChange(value) {
      this.paymentId = value;
      this.paymentItem = this.payment.find((item) => item.id === value) || {};
      this.computeCount();
    },

    radioClick() {
      this.radioSelected = !this.radioSelected;
    },
    toAgreement() {
      uni.navigateTo({
        url: `/nursingWorkerPages/pages/userAgreement/userAgreement?type=1`,
      });
    },
    toPatientList() {
      uni.navigateTo({
        url: "/nursingWorkerPages/pages/patientList/patientList",
      });
    },
  },
};
</script>

<style>
page {
  background-color: #f5f5f5;
  font-size: 28rpx;
  color: #333;
}
::v-deep.uni-icons {
  display: none !important;
}
::v-deep.uni-date-x {
  padding: 0 !important;
}
</style>

<style lang="scss" scoped>
$color-primary: #0bc5ae;
$color-danger: #ff4d4f;
$color-gray-300: #c1c1c1;
$color-gray-400: #999;
$color-gray-600: #666;
$color-gray-900: #333;
$spacing-xs: 10rpx;
$spacing-sm: 20rpx;
$spacing-md: 30rpx;
$spacing-lg: 40rpx;
$radius-sm: 8rpx;
$radius-md: 16rpx;
$radius-lg: 20rpx;
$border-color: #ececec;

.order-list {
  padding-bottom: 240rpx;
}

.section-header {
  font-size: 32rpx;
  margin: $spacing-md $spacing-md $spacing-xs;
  .section-title {
    font-size: 32rpx;
    font-weight: 700;
    color: $color-gray-900;
    padding-left: $spacing-xs;
    border-left: 4rpx solid $color-primary;
  }
}

.order-card,
.service-card,
.instructions-card {
  font-size: 32rpx;
  margin: $spacing-sm $spacing-md;
  background: #fff;
  border-radius: $radius-md;
  padding: $spacing-md;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.instructions-item {
  margin-bottom: $spacing-md;
  &:last-child {
    margin-bottom: 0;
  }
  .instructions-title {
    font-size: 30rpx;
    font-weight: 700;
    color: $color-gray-900;
    margin-bottom: $spacing-xs;
  }
  .instructions-content {
    .content-item {
      font-size: 32rpx;
      color: $color-gray-600;
      line-height: 1.8;
      margin-bottom: $spacing-xs;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .indent {
      text-indent: 48rpx;
    }
  }
}

.form-card {
  .form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: $spacing-md;
    &:last-child {
      margin-bottom: 0;
    }
    .form-label {
      font-size: 28rpx;
      font-weight: 500;
      color: $color-gray-900;
      margin-bottom: $spacing-xs;
      &.required::after {
        content: "*";
        color: $color-danger;
        margin-left: 4rpx;
      }
    }
    .form-content {
      width: 100%;
    }
  }

  .time-range-picker {
    width: 230rpx;
    padding: 0 $spacing-sm;
    height: 80rpx;
    border: 1rpx solid $border-color;
    border-radius: $radius-sm;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: $spacing-xs;
    transition: all 0.2s ease;

    &.placeholder {
      color: $color-gray-300;
    }
    &:active,
    &:focus-within {
      border-color: $color-primary;
      box-shadow: 0 0 0 2rpx rgba(11, 197, 174, 0.2);
    }

    .range-label {
      font-size: 14rpx;
      color: $color-gray-600;
      width: 220rpx;
    }
    .range-value {
      width: 100%;
      font-size: 28rpx;
      color: $color-gray-900;
      text-align: right;
      padding-right: 20rpx;
    }
  }

  .fixed-time {
    font-size: 28rpx;
    color: $color-gray-900;
    padding: 0 $spacing-sm;
    height: 80rpx;
    line-height: 80rpx;
    border: 1rpx solid $border-color;
    border-radius: $radius-sm;
    box-sizing: border-box;
    width: 220rpx;
    background-color: #f9f9f9;
  }

  .select-item {
    width: 100%;
    padding: $spacing-xs 0;
    .select-value {
      font-size: 28rpx;
      color: $color-gray-900;
      &.placeholder {
        color: $color-gray-300;
      }
    }
    .patient-info {
      .patient-main {
        display: flex;
        align-items: center;
        margin-bottom: $spacing-xs;
        .patient-name {
          font-size: 28rpx;
          font-weight: 500;
          margin-right: $spacing-xs;
        }
        .patient-tag {
          font-size: 24rpx;
          color: $color-gray-600;
        }
      }
      .patient-desc {
        font-size: 24rpx;
        color: $color-gray-600;
        line-height: 1.5;
      }
    }
  }

  .cycle-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    padding: 15rpx 0;
    cursor: pointer;
    transition: background-color 0.2s;
    justify-content: space-between;
    box-sizing: border-box;
    user-select: none;

    &:active {
      background-color: #f0f9f8;
    }
    &.active {
      background-color: #e6f7f5;
    }
    &:disabled {
      opacity: 0.6;
      pointer-events: none;
    }
    > * {
      pointer-events: none;
    }

    .cycle-label {
      font-size: 28rpx;
      color: $color-gray-600;
      width: 140rpx;
    }
    .cycle-value {
      font-size: 28rpx;
      color: $color-gray-900;
      flex: 1;
      text-align: left;
      margin-left: 20rpx;
      &.placeholder {
        color: $color-gray-300;
      }
    }
    .arrow-icon {
      font-size: 24rpx;
      color: $color-gray-400;
      margin-left: 10rpx;
    }
  }
  .cycle-count {
    font-size: 24rpx;
    color: $color-gray-600;
    margin-top: $spacing-xs;
    text-align: right;
  }

  .input-item {
    width: 100%;
    height: 80rpx;
    padding: 0 $spacing-sm;
    border: 1rpx solid $border-color;
    border-radius: $radius-sm;
    font-size: 28rpx;
    color: $color-gray-900;
    box-sizing: border-box;
    &::placeholder {
      color: $color-gray-300;
    }
  }

  .textarea-item {
    width: 100%;
    min-height: 200rpx;
    padding: $spacing-sm;
    border: 1rpx solid $border-color;
    border-radius: $radius-sm;
    font-size: 28rpx;
    color: $color-gray-900;
    box-sizing: border-box;
    line-height: 1.8;
  }
  .textarea-placeholder {
    color: $color-gray-300;
  }

  .payment-box {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-xs;
    .payment-item {
      min-width: 140rpx;
      padding: 10rpx $spacing-xs;
      background: #f1f1f1;
      border-radius: $radius-sm;
      font-size: 24rpx;
      text-align: center;
      color: $color-gray-600;
      &.selected {
        background: $color-primary;
        color: #fff;
      }
    }
  }
}

.service-card {
  .service-item {
    display: flex;
    flex-wrap: wrap;
    padding: $spacing-xs 0;
    border-bottom: 1rpx solid $border-color;
    &:last-child {
      border-bottom: none;
    }
    .service-label {
      width: 140rpx;
      font-size: 28rpx;
      color: $color-gray-600;
    }
    .service-value {
      flex: 1;
      font-size: 28rpx;
      color: $color-gray-900;
      line-height: 1.6;
    }
  }

  .notice-section {
    margin-top: $spacing-md;
    .notice-title {
      font-size: 30rpx;
      font-weight: 700;
      color: $color-gray-900;
      margin-bottom: $spacing-xs;
    }
    .notice-content {
      .notice-item {
        font-size: 24rpx;
        color: $color-gray-600;
        line-height: 1.8;
        margin-bottom: $spacing-xs;
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .promise-section {
    margin-top: $spacing-md;
    .promise-title {
      font-size: 30rpx;
      font-weight: 700;
      color: $color-gray-900;
      margin-bottom: $spacing-sm;
      text-align: center;
    }
    .promise-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      gap: $spacing-sm;
    }
    .promise-item {
      width: 48%;
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      .promise-icon {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: $spacing-xs;
      }
      .promise-name {
        font-size: 26rpx;
        font-weight: 500;
        color: $color-gray-900;
        margin-bottom: 4rpx;
      }
      .promise-desc {
        font-size: 22rpx;
        color: $color-gray-600;
      }
    }
  }
}

.instructions-card {
  margin: $spacing-sm $spacing-md $spacing-lg;
  .instructions-item {
    margin-bottom: $spacing-md;
    &:last-child {
      margin-bottom: 0;
    }
    .instructions-title {
      font-size: 32rpx;
      font-weight: 700;
      color: $color-gray-900;
      margin-bottom: $spacing-xs;
    }
    .instructions-content {
      .content-item {
        font-size: 32rpx;
        color: $color-gray-600;
        line-height: 1.8;
        margin-bottom: $spacing-xs;
        &:last-child {
          margin-bottom: 0;
        }
      }
      .indent {
        text-indent: 48rpx;
      }
    }
  }
}

.bottom-fixed-view {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1rpx solid $border-color;
  z-index: 99;

  .agreement-view {
    display: flex;
    align-items: center;
    padding: $spacing-xs $spacing-md;
    border-bottom: 1rpx solid $border-color;
    .select-button {
      margin-right: $spacing-xs;
    }
    .select-icon {
      width: 36rpx;
      height: 36rpx;
    }
    .agreement-text {
      font-size: 24rpx;
      color: $color-gray-600;
      .agreement-link {
        color: $color-primary;
        text-decoration: underline;
      }
    }
  }

  .pay-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-sm $spacing-md;
    .pay-info {
      display: flex;
      align-items: flex-end;
      .pay-label {
        font-size: 28rpx;
        color: $color-gray-600;
        margin-right: $spacing-xs;
      }
    }
    .pay-btn {
      width: 240rpx;
      height: 80rpx;
      background: $color-primary;
      color: #fff;
      font-size: 30rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .pay-btn:disabled {
      background: #b3e8e0;
      color: #fff;
    }
  }
}

// 确保时间选择器不被遮挡
::v-deep .u-datetime-picker {
  z-index: 9999 !important;
}
</style>
